package com.informa.hamcrest.matchers;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

import com.informa.utils.XmlUtils;

public class StringXPathMatcher extends TypeSafeMatcher<String> {

	private String xpath;
	
	public StringXPathMatcher(String xpath) {
		this.xpath = xpath;
	}
	
	@Override
	public boolean matchesSafely(String document) {
		try {
			Node node = DocumentHelper.parseText(document);
			return XmlUtils.exists(node, xpath);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
	}

	public void describeTo(Description description) {
		description.appendText("Node does not match xpath " + xpath);
	}
	
	public static StringXPathMatcher matchesXpath(String xpath) {
		return new StringXPathMatcher(xpath);
	}
	
}
